import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.PriorityQueue;

public class Leetcode2034 {
    public static void main(String[] args) {
        StockPrice stockPrice = new StockPrice();
        stockPrice.update(1, 10);
        stockPrice.update(2, 5);

        System.out.println(stockPrice.current());
        System.out.println(stockPrice.maximum());

        stockPrice.update(1, 3);

        System.out.println(stockPrice.maximum());

        stockPrice.update(4, 2);

        System.out.println(stockPrice.minimum());
    }

    static class StockPrice {
        int maxTimeStamp;
        Map<Integer, Integer> timeStampMap;
        PriorityQueue<int[]> maxDeap;
        PriorityQueue<int[]> minDeap;

        public StockPrice() {
            maxTimeStamp = 0;
            timeStampMap = new HashMap<>();
            minDeap = new PriorityQueue<>(Comparator.comparingInt(o -> o[0]));
            maxDeap = new PriorityQueue<>((o1, o2) -> o2[0] - o1[0]);
        }

        public void update(int timestamp, int price) {
            maxTimeStamp = Math.max(maxTimeStamp, timestamp);
            timeStampMap.put(timestamp, price);
            maxDeap.add(new int[]{price, timestamp});
            minDeap.add(new int[]{price, timestamp});
        }

        public int current() {
            return timeStampMap.get(maxTimeStamp);
        }

        public int maximum() {
            return getQueuePrice(maxDeap);
        }

        public int minimum() {
            return getQueuePrice(minDeap);
        }

        private int getQueuePrice(PriorityQueue<int[]> q) {
            while (!q.isEmpty()) {
                int price = q.peek()[0];
                int timeStamp = q.peek()[1];
                if (timeStampMap.get(timeStamp) == price) {
                    return price;
                }
                q.poll();
            }

            throw new NullPointerException();
        }

    }
}

